package com.bank.util;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;

import com.bank.code.RespCode;
import com.bank.entity.*;
import com.bank.dao.*;
import com.bank.exception.CommonException;

public class CommonUtil {
	
	public static  final String DEMAND_ACCT_SUBJECT = "100102";//活期账户科目
	
	public static final String  TIME_ACCT_SUBJECT = "100202";//定期账号科目
		
	public static  String  getWorkDate(){
		SystemWorkdateMapper systemWorkdateMapper = (SystemWorkdateMapper) SpringContextUtils.getBeanById("systemWorkdateMapper");
		List<SystemWorkdate> systemWorkdateList = systemWorkdateMapper.selectWorkdate();
		return systemWorkdateList.get(0).getCurr_wordate();
	}
	
	public static String getCurrentTime(){
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String   currentTime = df.format(new Date());
		return currentTime;
	}
	/**
	 * 获取柜员流水号
	 * @param tellerId 代号 
	 * @param transOri 交易机构
	 * @param workdate 工作日期
	 * @return 柜员流水号
	 * */
	@Transactional
	public static String getTellerSerno(String tellerId, String  transOri, String workdate){
		Logger logger = Logger.getLogger(CommonUtil.class);
		TellerMapper tellerMapper = (TellerMapper)SpringContextUtils.getBeanById("tellerMapper");
		if(tellerMapper != null){
			logger.debug("tellerMapper获取失败");
		}
		Teller   teller = tellerMapper.selectByPrimaryKey(tellerId);
		Integer serialNumber = teller.getSerial_number();
		String tellerSerialNumber = workdate+tellerId+serialNumber;   //流水号 = 交易日期+柜员代号+ 序号
		teller.setSerial_number(serialNumber+1);
		tellerMapper.updateByPrimaryKeySelective(teller);
		return tellerSerialNumber;
	}
	
	/**
	 * 密码加密
	 * @param  待加密密码
	 * @return 密文
	 * @throws CommonException 
	 * 
	 * */
	public static String passwordEncryption(String password) throws CommonException
	{
		MessageDigest md5;
		String ciphertext = null;
		try {
				md5 = MessageDigest.getInstance("SHA-256");
				byte[] srcBytes = password.getBytes();  
				md5.update(srcBytes);  
				ciphertext = new String(md5.digest());  
				return ciphertext;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new CommonException(RespCode.PASSWORD_ENCRYPT_FAIL, "加密失败");
		}  
    }	

	
	public static Subject  getSubjectInfo(String subject_number){
		Logger logger = Logger.getLogger(CommonUtil.class);
		SubjectMapper subjectMapper = (SubjectMapper)SpringContextUtils.getBeanById("subjectMapper");
		Subject  subject = subjectMapper.selectByPrimaryKey(subject_number);
		if(subject == null){
			logger.debug("科目号未配置");
		}
		return subject;
	}
}
